package com.foodorder.service;

import com.foodorder.entity.User;
import com.foodorder.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户服务类
 */
@Service
@RequiredArgsConstructor
public class UserService {
    
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    
    /**
     * 根据ID查找用户
     */
    public User findById(Long id) {
        return userRepository.findById(id).orElse(null);
    }
    
    /**
     * 根据邮箱查找用户
     */
    public User findByEmail(String email) {
        return userRepository.findByEmail(email).orElse(null);
    }
    
    /**
     * 根据微信OpenID查找用户
     */
    public User findByWxOpenId(String wxOpenId) {
        return userRepository.findByWxOpenId(wxOpenId).orElse(null);
    }
    
    /**
     * 保存用户
     */
    public User save(User user) {
        return userRepository.save(user);
    }
    
    /**
     * 获取所有用户
     */
    public List<User> findAll() {
        return userRepository.findAll();
    }
    
    /**
     * 删除用户
     */
    public void deleteById(Long id) {
        userRepository.deleteById(id);
    }
    
    /**
     * 检查邮箱是否已存在
     */
    public boolean existsByEmail(String email) {
        return userRepository.existsByEmail(email);
    }
    
    /**
     * 更新用户位置
     */
    public void updateUserLocation(Long userId, Double longitude, Double latitude) {
        User user = findById(userId);
        if (user != null) {
            user.setLongitude(longitude);
            user.setLatitude(latitude);
            save(user);
        }
    }
    
    /**
     * 验证邮箱
     */
    public void verifyEmail(Long userId) {
        User user = findById(userId);
        if (user != null) {
            user.setEmailVerified(true);
            save(user);
        }
    }
    
    /**
     * 管理员查询用户（支持分页和搜索）
     */
    public Page<User> findUsersForAdmin(String keyword, String status, String role, Pageable pageable) {
        if (keyword != null && !keyword.trim().isEmpty()) {
            return userRepository.findByNicknameContainingOrEmailContaining(keyword, keyword, pageable);
        }
        if (status != null && !status.trim().isEmpty()) {
            User.UserStatus userStatus = User.UserStatus.valueOf(status.toUpperCase());
            return userRepository.findByStatus(userStatus, pageable);
        }
        return userRepository.findAll(pageable);
    }
    
    /**
     * 创建用户
     */
    public User createUser(User user) {
        // 加密密码
        if (user.getPassword() != null) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());
        return userRepository.save(user);
    }
    
    /**
     * 更新用户
     */
    public User updateUser(User user) {
        User existingUser = findById(user.getId());
        if (existingUser != null) {
            // 更新字段
            existingUser.setNickname(user.getNickname());
            existingUser.setEmail(user.getEmail());
            existingUser.setPhone(user.getPhone());
            existingUser.setAvatar(user.getAvatar());
            existingUser.setGender(user.getGender());
            existingUser.setBirthday(user.getBirthday());
            existingUser.setUpdatedAt(LocalDateTime.now());
            
            // 如果有新密码，则加密
            if (user.getPassword() != null && !user.getPassword().isEmpty()) {
                existingUser.setPassword(passwordEncoder.encode(user.getPassword()));
            }
            
            return userRepository.save(existingUser);
        }
        return null;
    }
    
    /**
     * 批量删除用户
     */
    public void deleteByIds(List<Long> ids) {
        userRepository.deleteAllById(ids);
    }
    
    /**
     * 更新用户状态
     */
    public void updateStatus(Long userId, String status) {
        User user = findById(userId);
        if (user != null) {
            user.setStatus(User.UserStatus.valueOf(status.toUpperCase()));
            user.setUpdatedAt(LocalDateTime.now());
            userRepository.save(user);
        }
    }
    
    /**
     * 重置用户密码
     */
    public void resetPassword(Long userId, String newPassword) {
        User user = findById(userId);
        if (user != null) {
            user.setPassword(passwordEncoder.encode(newPassword));
            user.setUpdatedAt(LocalDateTime.now());
            userRepository.save(user);
        }
    }
    
    /**
     * 获取用户统计信息
     */
    public Map<String, Object> getUserStatistics() {
        Map<String, Object> stats = new HashMap<>();
        
        long totalUsers = userRepository.count();
        long activeUsers = userRepository.countByStatus(User.UserStatus.ACTIVE);
        long inactiveUsers = userRepository.countByStatus(User.UserStatus.INACTIVE);
        long bannedUsers = userRepository.countByStatus(User.UserStatus.BANNED);
        
        stats.put("totalUsers", totalUsers);
        stats.put("activeUsers", activeUsers);
        stats.put("inactiveUsers", inactiveUsers);
        stats.put("bannedUsers", bannedUsers);
        
        // 今日新增用户
        LocalDateTime today = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
        long todayNewUsers = userRepository.countByCreatedAtAfter(today);
        stats.put("todayNewUsers", todayNewUsers);
        
        return stats;
    }
} 